Nginx arg参数重定向
在工作中很少使用nginx的rewrite模块,每次写重定向都有些蛋疼,现在先记录下遇到过的arg重定向问题。
需求是这样的: 当访问a.com/s?a=xx&b=yy时跳转到b.com/test/s?a=xx&b=yy
我一开始是这么写的:
复制
rewrite ^/s\?a=(.*)&b=(.*)$ http://b.com/test/s?a=$1&b=$2 permanent;
后面发现匹配不了,查看rewrite日志,日志一直弹:
复制
"^/s\?a=(.*)\&b=(.*)$" does not match "/s"
后面试了用^/s/a=(.*)&b=(.*)$可以匹配/s/a=xx&b=yy,猜想应该是问号后是参数,不能直接用参数匹配。
通过问朋友与搜索查询,发现uri参数可以用$arg_参数名来代替,所以,上面的正确写法是:
复制
rewrite ^/s http://b.com/test/s?a=$arg_a&b=$arg_b? permanent;
后面又加了需求,需要在以上跳转的基础上再加上: 当访问a.com/s?a=xx&b=yy&c=zz时跳转到b.com/test/s?a=xx&b=yy&c=zz
这样我们就同时需要满足两个需求,我们可以这么写:
复制
rewrite ^/s http://b.com/test/s?a=$arg_a&b=$arg_b? permanent;
if ($arg_c) {
rewrite ^/s http://b.com/test/s?a=$arg_a&b=$arg_b&c=$arg_c? permanent;
}
但其实面对上面这种情况,我们可以直接使用$args,$args的值是参数组,比如a.com/s?a=xx&b=yy的$args值为a=xx&b=yy,所以上面的写法可以统一为:
复制
rewrite ^/s http://b.com/test/s?$args? permanent;
无论是两个参数、三个参数还是更多,只要重定向的参数组是一样的,都可以这样写。
或者还可以写作:
复制
rewrite ^/s http://b.com/test/s permanent;
如果你细心的话,会注意到之前的例子最后都有加?尾缀,因为不加的话参数会自动加到最后,所以如上的写法也可以正确重定向。
再改下需求,如果我们要做到: 当访问a.com/s?a=xx&b=yy时跳转到b.com/test/s?a=xx0&b=yy1
那么首先我们就不能再用$args,因为a=xx&b=yy不同于a=xx0&b=yy1,在这里我们可以用set来设置变量:
复制
set $arg_a "${arg_a}0"
set $arg_b "${arg_b}1"
rewrite ^/s http://b.com/test/s?a=$arg_a&b=$arg_b? permanent;
总结:
复制
//尾缀不加?重定向,s后参数会自动加到test/s后
rewrite ^/s http://b.com/test/s permanent;
//尾缀加?重定向,s后参数不会自动加到test后,需要手动调用"$arg_参数名"或"$args"
rewrite ^/s http://b.com/test/s?a=$arg_a&b=$arg_b? permanent;
rewrite ^/s http://b.com/test/s?$args? permanent;
//尾缀直接加?重定向时不带参数
rewrite ^/s http://b.com/test? permanent;